package com.zondy.mapgis.android.frag;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zondy.mapgis.android.activity.MapActivity;
import com.zondy.mapgis.android.annotation.Annotation;
import com.zondy.mapgis.android.annotation.AnnotationView;
import com.zondy.mapgis.android.base.BaseFragment;
import com.zondy.mapgis.android.graphic.GraphicImage;
import com.zondy.mapgis.android.graphic.GraphicMultiPoint;
import com.zondy.mapgis.android.graphic.GraphicPolylin;
import com.zondy.mapgis.android.graphic.GraphicsOverlay;
import com.zondy.mapgis.android.internal.utils.ToastUtil;
import com.zondy.mapgis.android.mapview.MapView;
import com.zondy.mapgis.android.mapview.MapView.MapViewAnnotationListener;
import com.zondy.mapgis.android.mapview.MapView.MapViewTapListener;
import com.zondy.mapgis.android.utils.MapUtil;
import com.zondy.mapgis.core.geometry.Dot;
import com.zondy.mapgis.core.srs.SRefData;
import com.zondy.mapgis.explorer.MapApplication;
import com.zondy.mapgis.explorer.R;

/**
 * 距离测量
 * @author fjl
 *
 */
public class MeasureLengthFrag extends BaseFragment implements OnClickListener,MapViewTapListener,MapViewAnnotationListener
{

	private String TAG = this.getClass().getSimpleName();
	private MapActivity mMapActivity = null;
	private MapView mMapView = null;

	// 添加到地图上的Graphic
	private GraphicsOverlay mGraphicLayer = null;
	private GraphicMultiPoint mGraphicMultiPoint = null;
	private GraphicPolylin mGraphicPolylin = null;
	private List<Dot> mDotLst = new ArrayList<Dot>();
	/**存放距离测量值List**/
	private List<Double> mDisLst = new ArrayList<Double>();
	private List<Annotation> mAnnotationLst = new ArrayList<Annotation>();
	
	private Annotation mStartAnnotation = null;
	private Annotation mLengthAnnotation = null;
	private AnnotationView annotationView = null;
	private View mCalloutView = null;
	private Bitmap mBlueBmp;
	private Bitmap mRedBmp;
	private GraphicImage mGraphicStartImg = null;
	private Bitmap mStartBmp;

	private TextView mTitleTxt = null;
	private ImageView mRedoBtn = null;

	@Override
	public int bindLayout()
	{
		return R.layout.measure_length_frag;
	}

	@Override
	public void initView(View view)
	{
		mTitleTxt = (TextView) view.findViewById(R.id.title_text);
		mTitleTxt.setText("点击地图开始测量");
		mRedoBtn = (ImageView) view.findViewById(R.id.redo_btn);

		view.findViewById(R.id.title_back).setOnClickListener(this);
		view.findViewById(R.id.finish_measure_btn).setOnClickListener(this);
		mRedoBtn.setOnClickListener(this);
		
		mBlueBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ico_draw_point_blue);
		mRedBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ico_draw_point_red);
		mStartBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ico_result_location_green);
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public void doBusiness(Context mContext)
	{
		mMapActivity = MapApplication.getApp().getMapActivity();
		mMapView = mMapActivity.mMapView;
		SRefData sRefData = mMapView.getMap().getSRSInfo();
		if(sRefData.getSRSName().equalsIgnoreCase("WGS_84_MCT") || sRefData.getSRSName().equalsIgnoreCase("WGS_1984_Web_Mercator") || sRefData.getSRSName().equalsIgnoreCase("WGS_1984"))
		{
			mMapView.setTapListener(this);
			mMapView.setAnnotationListener(this);
			mGraphicLayer = mMapView.getGraphicsOverlay();

			if (mGraphicMultiPoint == null)
			{
				mGraphicMultiPoint = new GraphicMultiPoint();
				mGraphicMultiPoint.setColor(Color.BLUE);
				mGraphicMultiPoint.setPointSize(6);
			}
			if (mGraphicPolylin == null)
			{
				mGraphicPolylin = new GraphicPolylin();
				mGraphicPolylin.setColor(R.color.green);
				mGraphicPolylin.setLineWidth(10.0f);
			}
			if(mGraphicStartImg == null)
			{
				mGraphicStartImg = new GraphicImage();
				mGraphicStartImg.setPoint(new Dot(0.0f, 0.0f));
			}

			mGraphicLayer.addGraphic(mGraphicMultiPoint);
			mGraphicLayer.addGraphic(mGraphicPolylin);
			mGraphicLayer.addGraphic(mGraphicStartImg);
		}
		else
		{
			ToastUtil.showToast(mContext, "暂时不支持该空间参考系测距");
		}
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.finish_measure_btn:
			mMapActivity.removeFragment(TAG, null);
			mMapActivity.mMapBottomContent.setVisibility(View.VISIBLE);
			mMapActivity.mMapRightContent.setVisibility(View.VISIBLE);
			
//			String title = mStartAnnotation.getTitle();
//			mStartAnnotation.showAnnotationView();
			break;

		case R.id.title_back:
			mMapActivity.removeFragment(TAG, null);
			mMapActivity.mMapBottomContent.setVisibility(View.VISIBLE);
			mMapActivity.mMapRightContent.setVisibility(View.VISIBLE);
			break;

		case R.id.redo_btn:
			reMeasure();
			break;
		default:
			break;
		}
	}

	@Override
	public void mapViewTap(PointF viewPoint)
	{
		Dot tapDot = mMapView.viewPointToMapPoint(viewPoint);
		mDotLst.add(tapDot);
		if (mDotLst.size() > 0)
		{
			mRedoBtn.setVisibility(View.VISIBLE);
		}

		if(mDotLst.size() == 1)
		{
			mStartAnnotation = MapUtil.addAnnotionByDot(getContext(), mMapView, String.valueOf(mDotLst.size()), "起点", null, mDotLst.get(0), mRedBmp);
			mAnnotationLst.add(mStartAnnotation);
			mStartAnnotation.showAnnotationView();
			updateGraphicImg(mGraphicStartImg, mStartBmp, mDotLst.get(0));
		}
		if(mDotLst.size() > 1)
		{
			//计算距离
			double dis = MapUtil.dotDistance(mDotLst.get(mDotLst.size() - 2), mDotLst.get(mDotLst.size() -1));
			mDisLst.add(dis);
			
			mLengthAnnotation = MapUtil.addAnnotionByDot(getContext(), mMapView, String.valueOf(mDotLst.size()), calSum(mDisLst), null, mDotLst.get(mDotLst.size()- 1), mRedBmp);
			mAnnotationLst.add(mLengthAnnotation);
			mLengthAnnotation.showAnnotationView();
			Log.e(TAG, "索引：" + mMapView.getAnnotationsOverlay().indexOf(mLengthAnnotation));
		}
			
		mGraphicMultiPoint.setPoints(mDotLst);
		mGraphicPolylin.setPoints(mDotLst);
		mMapView.refresh();

	}

	@Override
	public void onDestroyView()
	{
		mMapView.setTapListener(null);
//		mGraphicLayer.removeAllGraphics();
		if(mGraphicMultiPoint != null)
		{
			mGraphicLayer.removeGraphic(mGraphicMultiPoint);
		}
		if(mGraphicPolylin != null)
		{
			mGraphicLayer.removeGraphic(mGraphicPolylin);
		}
		if(mGraphicStartImg != null)
		{
			mGraphicLayer.removeGraphic(mGraphicStartImg);
		}
		mMapView.getAnnotationsOverlay().removeAllAnnotations();
		mMapView.refresh();
		super.onDestroyView();
	}

	@Override
	public boolean goback()
	{
		return false;
	}

	@Override
	public boolean isLocked()
	{
		return false;
	}

	@Override
	public String getName()
	{
		return TAG;
	}

	/**
	 * 地图标注监听
	 */
	@Override
	public void mapViewClickAnnotation(MapView mapView, Annotation annotation)
	{

	}

	@Override
	public boolean mapViewWillShowAnnotationView(MapView mapView, AnnotationView annotationView)
	{
		return false;
	}

	@Override
	public boolean mapViewWillHideAnnotationView(MapView mapView, AnnotationView annotationView)
	{
		return false;
	}

	@Override
	public AnnotationView mapViewViewForAnnotation(MapView mapView, Annotation annotation)
	{
		annotationView = new AnnotationView(annotation, getContext());
		annotationView.setPanToMapViewCenter(false);
		
		mCalloutView = LayoutInflater.from(getContext()).inflate(R.layout.annotation_calloutview, null);
		annotationView.setCalloutView(mCalloutView);
		
		ImageView closeCalloutView = (ImageView) mCalloutView.findViewById(R.id.close_iv);
		TextView title = (TextView) mCalloutView.findViewById(R.id.callout_titile_tv);
		title.setText("起点");
		//Annotation显示样式
		showAnnotationStyle(mAnnotationLst);
		if(mDotLst.size() == 1 && mStartAnnotation != null)
		{
			title.setText(mStartAnnotation.getTitle());
		}
		if(mDotLst.size() > 1 && annotation != null)
		{
			title.setText(annotation.getTitle());
		}
		closeCalloutView.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				if(mDotLst.size() == 1)
				{
					reMeasure();
				}
				if(mDotLst.size() > 1)
				{
					//移除上一个Annotation
//					mMapView.getAnnotationsOverlay().removeAnnotation(mDotLst.size() - 1);
					mMapView.getAnnotationsOverlay().removeAnnotation(mAnnotationLst.get(mDotLst.size() - 1));
					mDotLst.remove(mDotLst.size() - 1);
					mDisLst.remove(mDisLst.size() - 1);
					
					mGraphicMultiPoint.setPoints(mDotLst);
					mGraphicPolylin.setPoints(mDotLst);
					
					mAnnotationLst.remove(mAnnotationLst.size() - 1);
					mAnnotationLst.get(mDotLst.size() -1).showAnnotationView();
//					mMapView.getAnnotationsOverlay().getAnnotation(mDotLst.size() -1).showAnnotationView();
				}
				mMapView.refresh();
			}
		});
		
		
		return annotationView;
	}

	@Override
	public void mapViewClickAnnotationView(MapView mapView, AnnotationView annotationView)
	{

	}
	
	/**
	 * 显示Annotation样式（最后一个红色，其余显示为的蓝色）
	 * @param annotationLst
	 */
	private void showAnnotationStyle(List<Annotation> annotationLst)
	{
		if(annotationLst.size()  > 1)
		{
			for(int i = 0; i < annotationLst.size() - 1; i++ )
			{
				annotationLst.get(i).setImage(mBlueBmp);
			}
			annotationLst.get(annotationLst.size() - 1).setImage(mRedBmp);
		}
	}
	
	/**
	 * 重新测量
	 */
	private void reMeasure()
	{
		mGraphicMultiPoint.removeAllPoints();
		mGraphicPolylin.removeAllPoints();
		mGraphicStartImg.setPoint(new Dot(0.0, 0.0));
//		mStartAnnotation.hideAnnotationView();
//		mLengthAnnotation.hideAnnotationView();
		mMapView.getAnnotationsOverlay().removeAllAnnotations();
		mDotLst.clear();
		mDisLst.clear();
		mAnnotationLst.clear();
		mMapView.refresh();
	}

	/**
	 * 计算数组中数据之和
	 * @param lst
	 * @return
	 */
	private String calSum(List<Double> lst)
	{
		double dis = 0.0;
		String strDis = "0.0km";
		for(int i = 0 ;i  < lst.size();i++)
		{
			dis += lst.get(i);
		}
		DecimalFormat df = new DecimalFormat("###0.0");
		strDis = df.format(dis / 1000) + "km";
		Log.d(TAG, "计算数组中距离之和:"+strDis);
		
		return strDis;
	}
	/**
	 * 更新地图上添加的GraphicImage
	 * @param graphicImage
	 * @param bitmap
	 * @param curPoint
	 */
	public void updateGraphicImg(GraphicImage graphicImage,Bitmap bitmap,Dot curPoint)
	{
		graphicImage.setImage(bitmap);
		graphicImage.setPoint(curPoint);
		graphicImage.setAnchorPoint(new PointF(0.5f, 0.0f));
	}
}
